package pwd.allen.web.controller;

import com.alibaba.druid.stat.DruidStatManagerFacade;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import pwd.allen.annotation.MyAnnotation;
import pwd.allen.entity.Person;
import pwd.allen.service.PersonService;
import pwd.allen.web.websocket.MyWebSocketHandler;

import java.io.IOException;

/**
 * @author 门那粒沙
 * @create 2020-02-04 21:18
 **/
@Log4j2
@RestController
@RequestMapping("person")
public class PersonController {

    @Autowired
    private PersonService personService;

    /**
     * @param id
     * @return
     */
    @MyAnnotation
    @RequestMapping(value = "getJSON/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Person getJSONById(@PathVariable("id") Integer id) {
        Person person = personService.getById(id);
        System.out.println(person);
        return person;
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "getXML", produces = MediaType.APPLICATION_XML_VALUE)
    public Person getXMLById(@RequestParam("id") Integer id) {
        Person person = personService.getById(id);
        return person;
    }


    @GetMapping("/test/{token}")
    public Object testWebSocketSession(@PathVariable("token")String token) throws IOException {
        WebSocketSession webSocketSession = MyWebSocketHandler.map_session.get(token);
        if (webSocketSession != null) {
            webSocketSession.sendMessage(new TextMessage("fuck you!"));
        }
        return "测试通过token获取保存的websocket连接，通过连接向客户端回复消息";
    }

    @PostMapping("/set")
    public Object setPerson(@RequestBody Person person) {
        return person;
    }

    /**
     * Druid 的监控数据可以在开启 StatFilter 后通过 DruidStatManagerFacade 进行获取，获取到监控数据之后我们便可以将其暴露给我们自己的监控系统进行使用。Druid 默认的监控系统数据也来源于此。
     * @return
     */
    @GetMapping(value = "/druid-stat", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object druidStat() {
        // 该方法可以获取所有数据源的监控数据
        // 除此之外 DruidStatManagerFacade 还提供了一些其他方法，我们可以按需选择使用。
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }
}
